package pri.hillchen.std.netty.timeserver;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 16:55 2018/3/30 0030.
 */
public class TimeClientHandler extends ChannelHandlerAdapter {
    private  final  ByteBuf firstMessage;
    public TimeClientHandler() {
        byte[] req = TimeServerHandler.QUERY_TIME_COMMAND.getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req);
        System.out.println("Now is:" + body);

        //获取到当前时间后要立即退出，否则客户端不会关闭。
        if(ctx != null){
            ctx.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
